import {
    getCurrentUserPagePermissionsApi,
    getCurrentUserPagePermissionsFail,
    getCurrentUserPagePermissionsSuccess
} from 'Shared/actions/currentUserContext';
import {PAGE_CODE} from './constants';
import {getPathById} from './utils';
import {workItemCategoryStatus} from '../Enum';
import * as api from './api';
/*==============================初始化API================================= */
export const GET_INIT_BEGIN = 'GET_INIT_BEGIN';
export const GET_INIT_SUCCESS = 'GET_INIT_SUCCESS';
export const GET_INIT_FAIL = 'GET_INIT_FAIL';
export const getInitDataBegin = () => ({
    type: GET_INIT_BEGIN
});
export const getInitDataSuccess = data => ({
    type: GET_INIT_SUCCESS,
    data,
});
export const getInitDataFail = () => ({
    type: GET_INIT_FAIL,
});
export const getInitData = (code = PAGE_CODE) => dispatch => {
    dispatch(getInitDataBegin());
    const init = api.initQuery().then(res => {
        if(res.ok)
            dispatch(getInitDataSuccess(res.data));
        else
            dispatch(getInitDataFail());
        return res.ok;
    });
    const permissions = getCurrentUserPagePermissionsApi(code).then(res => {
        if(res.isOk) dispatch(getCurrentUserPagePermissionsSuccess(res.data));
        else dispatch(getCurrentUserPagePermissionsFail(res.statusCode, res.message));
        return res.isOk;
    });
    return Promise.all([init, permissions]).then(values => values[0] && values[1]);
};

export const GET_CATEGORY_BEGIN = 'GET_CATEGORY_BEGIN';
export const GET_CATEGORY_SUCCESS = 'GET_CATEGORY_SUCCESS';
export const GET_CATEGORY_FAIL = 'GET_CATEGORY_FAIL';
export const getCategoryBegin = () => ({
    type: GET_CATEGORY_BEGIN
});

export const getCategorySuccess = (data, parentId) => (dispatch, getState) => {
    const trees = getState().getIn(['page', 'domainData', 'categories', 'data']).toJS();
    const path = getPathById(trees, parentId) || [];
    const newData = parentId ? data.map(item => {
        item.parentId = parentId;
        return item;
    }) : data;
    return dispatch({
        type: GET_CATEGORY_SUCCESS,
        data: newData,
        path
    });
};
export const getCategoryFail = () => ({
    type: GET_CATEGORY_FAIL,
});
export const getTopCategories = (forceRefresh = true) => (dispatch, getState) => {
    if(!forceRefresh) {
        const categories = getState().getIn(['page', 'domainData', 'categories', 'data']);
        if(categories && !categories.isEmpty())
            return Promise.resolve(true);
    }
    dispatch(getCategoryBegin());
    return api.getCategoriesTop().then(res => {
        if(res.ok) {
            const {content = []} = res.data;
            const data = content.map(item => ({
                items: [],
                ...item
            }));
            dispatch(getCategorySuccess(data || []));
        } else
            dispatch(getCategoryFail());
        return res.ok;
    });
};

export const getCategoryChildren = parentId => dispatch =>
    // dispatch(getCategoryBegin());
    api.getCategories(parentId).then(res => {
        if(res.ok) {
            const {content = []} = res.data;
            const data = content.map(item => ({
                items: [],
                ...item
            }));
            dispatch(getCategorySuccess(data, parentId));
        } else
            dispatch(getCategoryFail());
        return res.ok;
    })
;
/*==============================查询列表================================= */

export const GET_WORKITEMS_BEGIN = 'GET_WORKITEMS_BEGIN';
export const GET_WORKITEMS_SUCCESS = 'GET_WORKITEMS_SUCCESS';
export const GET_WORKITEMS_FAIL = 'GET_WORKITEMS_FAIL';
export const getWorkItemsBegin = () => ({
    type: GET_WORKITEMS_BEGIN
});
export const getWorkItemsSuccess = (data, condition) => ({
    type: GET_WORKITEMS_SUCCESS,
    data,
    condition
});
export const getWorkItemsFail = () => ({
    type: GET_WORKITEMS_FAIL,
}); //获取列表

export const getWorkItems = condition => dispatch => {
    dispatch(getWorkItemsBegin());
    return api.getWorkItems(condition).then(res => {
        if(res.ok)
            dispatch(getWorkItemsSuccess(res.data, condition));
        else
            dispatch(getWorkItemsFail());
        return res.ok;
    });
}; //按钮搜索

export const querySearch = () => (dispatch, getState) => {
    const condition = getState()
        .getIn(['page', 'appState', 'queryCondition'])
        .toJS();
    dispatch(getWorkItems(condition));
}; //分页排序搜索

export const tableSearch = page => (dispatch, getState) => {
    const query = getState()
        .getIn(['page', 'appState', 'queryBySort'])
        .toJS();
    const condition = Object.assign({}, query, page);
    dispatch(getWorkItems(condition));
};


export const categorySearch = id => (dispatch, getState) => {
    const condition = getState().getIn(['page', 'appState', 'queryBySort']).toJS();
    condition.workItemCategoryId = id;
    return dispatch(getWorkItems(condition));
};

/*==============================导出================================= */
export const exportData = () => (dispatch, getState) => {
    const {pageIndex, pageSize, ...props} = getState()
        .getIn(['page', 'appState', 'queryCondition'])
        .toJS() || {};
    return api.exportWorkItem(props);
};
//重置查询条件

export const RESET_QUERY_PANEL = 'RESET_QUERY_PANEL';
export const resetQueryPanel = () => ({
    type: RESET_QUERY_PANEL,
});
export const SAVE_QUERY_CONDITION = 'SAVE_QUERY_CONDITION';
export const saveQueryCondition = (name, value) => ({
    type: SAVE_QUERY_CONDITION,
    name,
    value
});

/* =======================获取详情================================== */
export const GET_DETAIL_BEGIN = 'GET_DETAIL_BEGIN';
export const GET_DETAIL_SUCCESS = 'GET_DETAIL_SUCCESS';
export const GET_DETAIL_FAIL = 'GET_DETAIL_FAIL';
export const getDetailBegin = () => ({
    type: GET_DETAIL_BEGIN
});
export const getDetailSuccess = data => ({
    type: GET_DETAIL_SUCCESS,
    data
});
export const getDetailFail = () => ({
    type: GET_DETAIL_FAIL,
});

export const getDetail = id => dispatch => {
    dispatch(getDetailBegin());
    return api.getWorkItemDetail(id).then(res => {
        if(res.ok)
            dispatch(getDetailSuccess(res.data));
        else
            dispatch(getDetailFail());
        return res;
    });
};

/*==============================更新维修项目的工时信息================================ */
export const onClickUpdateLaborhour = (id, data) => dispatch => api.updateLaborhour(id, data).then(res => res.ok);
/*==============================更新维修项目对应的辅助维修项目================================ */
export const onClickUpdateAssist = (id, data) => dispatch => api.updateAssist(id, data).then(res => res.ok);

export const SELECT_PC_QUERY = 'SELECT_PC_QUERY';
export const selectPC = data => ({
    type: SELECT_PC_QUERY,
    data: {
        productCategoryId: data.id,
        productCategoryCode: data.code,
        productCategoryName: data.name,
    }
});

/*==============================高级查询================================= */

export const GET_WPC_BEGIN = 'GET_WPC_BEGIN';
export const GET_WPC_SUCCESS = 'GET_WPC_SUCCESS';
export const GET_WPC_FAIL = 'GET_WPC_FAIL';
export const getWPCBegin = () => ({
    type: GET_WPC_BEGIN
});
export const getWPCSuccess = (data, condition) => ({
    type: GET_WPC_SUCCESS,
    data,
    condition
});
export const getWPCFail = () => ({
    type: GET_WPC_FAIL,
}); //获取列表

export const getWPCs = condition => dispatch => {
    dispatch(getWPCBegin());
    return api.getWPC(condition).then(res => {
        if(res.ok)
            dispatch(getWPCSuccess(res.data, condition));
        else
            dispatch(getWPCFail());
        return res.ok;
    });
}; //按钮搜索

//重置查询条件
export const RESET_HIGH_QUERY_PANEL = 'RESET_QUERY_PANEL';
export const resetHighQueryPanel = () => ({
    type: RESET_HIGH_QUERY_PANEL,
});

//修改查询条件
export const SAVE_HIGH_QUERY_CONDITION = 'SAVE_HIGH_QUERY_CONDITION';
export const saveHighQueryCondition = (name, value) => ({
    type: SAVE_HIGH_QUERY_CONDITION,
    name,
    value
});
/*==============================新增维修项目分类================================ */

export const ADD_CATEGORY = 'ADD_CATEGORY';
export const onClickAddCategory = data => (dispatch, getState) => api.addCategory(data).then(res => {
    if(res.ok) {
        const {parentId, typeId, ...props} = data;
        const trees = getState().getIn(['page', 'domainData', 'categories', 'data']).toJS();
        const types = getState().getIn(['page', 'domainData', 'initData', 'workItemCategoryTypes']).toJS();
        const path = getPathById(trees, parentId) || [];
        const {isLeaf, name} = types.find(item => item.id === typeId) || {};
        dispatch({
            type: ADD_CATEGORY,
            path,
            data: {
                ...props,
                ...res.data,
                isLeaf,
                typeName: name,
                typeId,
                status: workItemCategoryStatus.生效,
                items: [],
                isNew: true
            }
        });
    }
    return res.ok;
});

/*==============================编辑维修项目分类================================ */
export const UPDATE_CATEGORY = 'UPDATE_CATEGORY';
export const updateCategory = (id, data) => (dispatch, getState) => {
    const trees = getState().getIn(['page', 'domainData', 'categories', 'data']).toJS();
    const path = getPathById(trees, id) || [];
    dispatch({
        type: UPDATE_CATEGORY,
        path,
        data
    });
};
export const queryHighSearch = () => (dispatch, getState) => {
    const condition = getState()
        .getIn(['page', 'appState', 'queryHighCondition'])
        .toJS();
    const {productCategoryCode, productCategoryName, ...props} = condition;
    dispatch(getWPCs(props));
}; //分页排序搜索

export const tableHighSearch = page => (dispatch, getState) => {
    const query = getState()
        .getIn(['page', 'appState', 'queryHighBySort'])
        .toJS();
    const condition = Object.assign({}, query, page);
    dispatch(getWPCs(condition));
};


export const categoryHighSearch = id => (dispatch, getState) => {
    const condition = getState().getIn(['page', 'appState', 'queryHighBySort']).toJS();
    condition.workItemCategoryId = id;
    return dispatch(getWPCs(condition));
};
